home *** CD-ROM | disk | FTP | other *** search
/ Programming an RTS Game with Direct3D / Programming an RTS Game with Direct3D.iso / Examples / Chapter 5 / Example 5.10 / terrain.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2006-07-12  |  25.3 KB  |  927 lines

  1. #include "terrain.h"
  2. #include "camera.h"
  3.  
  4. const DWORD TERRAINVertex::FVF = D3DFVF_XYZ | D3DFVF_NORMAL | D3DFVF_TEX2;
  5.  
  6. //////////////////////////////////////////////////////////////////////////////////////////
  7. //                                    PATCH                                                //
  8. //////////////////////////////////////////////////////////////////////////////////////////
  9.  
  10. PATCH::PATCH()
  11. {
  12.     m_pDevice = NULL;
  13.     m_pMesh = NULL;
  14. }
  15. PATCH::~PATCH()
  16. {
  17.     Release();
  18. }
  19.  
  20. void PATCH::Release()
  21. {
  22.     if(m_pMesh != NULL)
  23.         m_pMesh->Release();
  24.     m_pMesh = NULL;
  25. }
  26.  
  27. HRESULT PATCH::CreateMesh(TERRAIN &ter, RECT source, IDirect3DDevice9* Dev)
  28. {
  29.     if(m_pMesh != NULL)
  30.     {
  31.         m_pMesh->Release();
  32.         m_pMesh = NULL;
  33.     }
  34.  
  35.     try
  36.     {
  37.         m_pDevice = Dev;
  38.         m_mapRect = source;
  39.  
  40.         int width = source.right - source.left;
  41.         int height = source.bottom - source.top;
  42.         int nrVert = (width + 1) * (height + 1);
  43.         int nrTri = width * height * 2;
  44.  
  45.         if(FAILED(D3DXCreateMeshFVF(nrTri, nrVert, D3DXMESH_MANAGED, TERRAINVertex::FVF, m_pDevice, &m_pMesh)))
  46.         {
  47.             debug.Print("Couldn't create mesh for PATCH");
  48.             return E_FAIL;
  49.         }
  50.  
  51.         m_BBox.max = D3DXVECTOR3(-10000.0f, -10000.0f, -10000.0f);
  52.         m_BBox.min = D3DXVECTOR3(10000.0f, 10000.0f, 10000.0f);
  53.  
  54.         //Create vertices
  55.         TERRAINVertex* ver = 0;
  56.         m_pMesh->LockVertexBuffer(0,(void**)&ver);
  57.         for(int z=source.top, z0 = 0;z<=source.bottom;z++, z0++)
  58.             for(int x=source.left, x0 = 0;x<=source.right;x++, x0++)
  59.             {
  60.                 MAPTILE *tile = ter.GetTile(x, z);
  61.  
  62.                 D3DXVECTOR3 pos = D3DXVECTOR3(x, tile->m_height, -z);
  63.                 D3DXVECTOR2 alphaUV = D3DXVECTOR2(x / (float)ter.m_size.x, z / (float)ter.m_size.y);        //Alpha UV
  64.                 D3DXVECTOR2 colorUV = alphaUV * 8.0f;                                                    //Color UV
  65.  
  66.                 ver[z0 * (width + 1) + x0] = TERRAINVertex(pos, ter.GetNormal(x, z), alphaUV, colorUV);
  67.  
  68.                 //Calculate bounding box bounds...
  69.                 if(pos.x < m_BBox.min.x)m_BBox.min.x = pos.x;
  70.                 if(pos.x > m_BBox.max.x)m_BBox.max.x = pos.x;
  71.                 if(pos.y < m_BBox.min.y)m_BBox.min.y = pos.y;
  72.                 if(pos.y > m_BBox.max.y)m_BBox.max.y = pos.y;
  73.                 if(pos.z < m_BBox.min.z)m_BBox.min.z = pos.z;
  74.                 if(pos.z > m_BBox.max.z)m_BBox.max.z = pos.z;
  75.             }
  76.         m_pMesh->UnlockVertexBuffer();
  77.  
  78.         //Calculate Indices
  79.         WORD* ind = 0;
  80.         m_pMesh->LockIndexBuffer(0,(void**)&ind);    
  81.         int index = 0;
  82.  
  83.         for(int z=source.top, z0 = 0;z<source.bottom;z++, z0++)
  84.             for(int x=source.left, x0 = 0;x<source.right;x++, x0++)
  85.             {
  86.                 //Triangle 1
  87.                 ind[index++] =   z0   * (width + 1) + x0;
  88.                 ind[index++] =   z0   * (width + 1) + x0 + 1;
  89.                 ind[index++] = (z0+1) * (width + 1) + x0;        
  90.  
  91.                 //Triangle 2
  92.                 ind[index++] = (z0+1) * (width + 1) + x0;
  93.                 ind[index++] =   z0   * (width + 1) + x0 + 1;
  94.                 ind[index++] = (z0+1) * (width + 1) + x0 + 1;
  95.             }
  96.  
  97.         m_pMesh->UnlockIndexBuffer();
  98.  
  99.         //Set Attributes
  100.         DWORD *att = 0, a = 0;
  101.         m_pMesh->LockAttributeBuffer(0,&att);
  102.         memset(att, 0, sizeof(DWORD)*nrTri);
  103.         m_pMesh->UnlockAttributeBuffer();
  104.     }
  105.     catch(...)
  106.     {
  107.         debug.Print("Error in PATCH::CreateMesh()");
  108.         return E_FAIL;
  109.     }
  110.  
  111.     return S_OK;
  112. }
  113.  
  114. void PATCH::Render()
  115. {
  116.     //Draw mesh
  117.     if(m_pMesh != NULL)
  118.         m_pMesh->DrawSubset(0);
  119. }
  120.  
  121. //////////////////////////////////////////////////////////////////////////////////////////
  122. //                                    TERRAIN                                                //
  123. //////////////////////////////////////////////////////////////////////////////////////////
  124.  
  125. TERRAIN::TERRAIN()
  126. {
  127.     m_pDevice = NULL;
  128.     m_pMapTiles = NULL;
  129. }
  130.  
  131. void TERRAIN::Init(IDirect3DDevice9* Dev, INTPOINT _size)
  132. {
  133.     m_pDevice = Dev;
  134.     m_size = _size;
  135.     m_pHeightMap = NULL;
  136.  
  137.     if(m_pMapTiles != NULL)    //Clear old maptiles
  138.         delete [] m_pMapTiles;
  139.  
  140.     //Create maptiles
  141.     m_pMapTiles = new MAPTILE[m_size.x * m_size.y];
  142.     memset(m_pMapTiles, 0, sizeof(MAPTILE)*m_size.x*m_size.y);
  143.  
  144.     //Clear old textures
  145.     for(int i=0;i<m_diffuseMaps.size();i++)
  146.         m_diffuseMaps[i]->Release();
  147.     m_diffuseMaps.clear();
  148.  
  149.     //Load textures
  150.     IDirect3DTexture9* grass = NULL, *mount = NULL, *snow = NULL;
  151.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/grass.jpg", &grass)))debug.Print("Could not load grass.jpg");
  152.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/mountain.jpg", &mount)))debug.Print("Could not load mountain.jpg");
  153.     if(FAILED(D3DXCreateTextureFromFile(Dev, "textures/snow.jpg", &snow)))debug.Print("Could not load snow.jpg");
  154.     m_diffuseMaps.push_back(grass);
  155.     m_diffuseMaps.push_back(mount);
  156.     m_diffuseMaps.push_back(snow);
  157.     m_pAlphaMap = NULL;
  158.     m_pLightMap = NULL;
  159.  
  160.     // Init font
  161.     D3DXCreateFont(m_pDevice, 40, 0, 0, 1, false,  
  162.                    DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, DEFAULT_QUALITY,
  163.                    DEFAULT_PITCH | FF_DONTCARE, "Arial Black", &m_pProgressFont);
  164.  
  165.     //Load pixel & vertex shaders
  166.     m_dirToSun = D3DXVECTOR3(1.0f, 0.6f, 0.5f);
  167.     D3DXVec3Normalize(&m_dirToSun, &m_dirToSun);
  168.  
  169.     m_terrainPS.Init(Dev, "shaders/terrain.ps", PIXEL_SHADER);
  170.     m_terrainVS.Init(Dev, "shaders/terrain.vs", VERTEX_SHADER);
  171.     m_vsMatW = m_terrainVS.GetConstant("matW");
  172.     m_vsMatVP = m_terrainVS.GetConstant("matVP");
  173.     m_vsDirToSun = m_terrainVS.GetConstant("DirToSun");
  174.  
  175.     m_objectPS.Init(Dev, "shaders/objects.ps", PIXEL_SHADER);
  176.     m_objectVS.Init(Dev, "shaders/objects.vs", VERTEX_SHADER);
  177.     m_objMatW = m_objectVS.GetConstant("matW");
  178.     m_objMatVP = m_objectVS.GetConstant("matVP");
  179.     m_objDirToSun = m_objectVS.GetConstant("DirToSun");
  180.     m_objMapSize = m_objectVS.GetConstant("mapSize");
  181.  
  182.     //Create white material    
  183.     m_mtrl.Ambient = m_mtrl.Specular = m_mtrl.Diffuse  = D3DXCOLOR(0.5f, 0.5f, 0.5f, 1.0f);
  184.     m_mtrl.Emissive = D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f);
  185.  
  186.     GenerateRandomTerrain(9);
  187. }
  188.  
  189. void TERRAIN::Release()
  190. {
  191.     for(int i=0;i<m_patches.size();i++)
  192.         if(m_patches[i] != NULL)
  193.             m_patches[i]->Release();
  194.  
  195.     m_patches.clear();
  196.  
  197.     if(m_pHeightMap != NULL)
  198.     {
  199.         m_pHeightMap->Release();
  200.         delete m_pHeightMap;
  201.         m_pHeightMap = NULL;
  202.     }
  203.  
  204.     m_objects.clear();
  205. }
  206.  
  207. void TERRAIN::GenerateRandomTerrain(int numPatches)
  208. {
  209.     try
  210.     {
  211.         Release();
  212.  
  213.         //Create two heightmaps and multiply them
  214.         m_pHeightMap = new HEIGHTMAP(m_size, 20.0f);
  215.         HEIGHTMAP hm2(m_size, 2.0f);
  216.  
  217.         m_pHeightMap->CreateRandomHeightMap(rand()%2000, 1.0f, 0.7f, 7);
  218.         hm2.CreateRandomHeightMap(rand()%2000, 2.5f, 0.8f, 3);
  219.  
  220.         hm2.Cap(hm2.m_maxHeight * 0.4f);
  221.  
  222.         *m_pHeightMap *= hm2;
  223.         hm2.Release();
  224.         
  225.         //Add objects
  226.         HEIGHTMAP hm3(m_size, 1.0f);
  227.         hm3.CreateRandomHeightMap(rand()%1000, 5.5f, 0.9f, 7);
  228.  
  229.         for(int y=0;y<m_size.y;y++)
  230.             for(int x=0;x<m_size.x;x++)
  231.             {
  232.                 if(m_pHeightMap->GetHeight(x, y) == 0.0f && hm3.GetHeight(x, y) > 0.7f && rand()%6 == 0)
  233.                     AddObject(0, INTPOINT(x, y));    //Tree
  234.                 else if(m_pHeightMap->GetHeight(x, y) >= 1.0f && hm3.GetHeight(x, y) > 0.9f && rand()%20 == 0)
  235.                     AddObject(1, INTPOINT(x, y));    //Stone
  236.             }
  237.  
  238.         hm3.Release();
  239.  
  240.         InitPathfinding();
  241.         CreatePatches(numPatches);
  242.         CalculateAlphaMaps();
  243.         CalculateLightMap();
  244.     }
  245.     catch(...)
  246.     {
  247.         debug.Print("Error in TERRAIN::GenerateRandomTerrain()");
  248.     }
  249. }
  250.  
  251. void TERRAIN::CreatePatches(int numPatches)
  252. {
  253.     try
  254.     {
  255.         //Clear any old patches
  256.         for(int i=0;i<m_patches.size();i++)
  257.             if(m_patches[i] != NULL)
  258.                 m_patches[i]->Release();
  259.         m_patches.clear();
  260.  
  261.         //Create new patches
  262.         for(int y=0;y<numPatches;y++)
  263.         {
  264.             Progress("Creating Terrain Mesh", y / (float)numPatches);
  265.  
  266.             for(int x=0;x<numPatches;x++)
  267.             {
  268.                 RECT r = {x * (m_size.x - 1) / (float)numPatches, 
  269.                           y * (m_size.y - 1) / (float)numPatches, 
  270.                         (x+1) * (m_size.x - 1) / (float)numPatches,
  271.                         (y+1) * (m_size.y - 1) / (float)numPatches};
  272.                         
  273.                 PATCH *p = new PATCH();
  274.                 p->CreateMesh(*this, r, m_pDevice);
  275.                 m_patches.push_back(p);
  276.             }
  277.         }
  278.     }
  279.     catch(...)
  280.     {
  281.         debug.Print("Error in TERRAIN::CreatePatches()");
  282.     }
  283. }
  284.  
  285. void TERRAIN::CalculateAlphaMaps()
  286. {
  287.     Progress("Creating Alpha Map", 0.0f);
  288.  
  289.     //Clear old alpha maps
  290.     if(m_pAlphaMap != NULL)
  291.         m_pAlphaMap->Release();
  292.  
  293.     //Create new alpha map
  294.     D3DXCreateTexture(m_pDevice, 128, 128, 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &m_pAlphaMap);
  295.  
  296.     //Lock the texture
  297.     D3DLOCKED_RECT sRect;
  298.     m_pAlphaMap->LockRect(0, &sRect, NULL, NULL);
  299.     BYTE *bytes = (BYTE*)sRect.pBits;
  300.     memset(bytes, 0, 128*sRect.Pitch);        //Clear texture to black
  301.  
  302.     for(int i=0;i<m_diffuseMaps.size();i++)
  303.         for(int y=0;y<sRect.Pitch / 4;y++)
  304.             for(int x=0;x<sRect.Pitch / 4;x++)
  305.             {
  306.                 int terrain_x = m_size.x * (x / (float)(sRect.Pitch / 4.0f));
  307.                 int terrain_y = m_size.y * (y / (float)(sRect.Pitch / 4.0f));
  308.                 MAPTILE *tile = GetTile(terrain_x, terrain_y);
  309.  
  310.                 if(tile != NULL && tile->m_type == i)
  311.                     bytes[y * sRect.Pitch + x * 4 + i] = 255;
  312.             }
  313.  
  314.     //Unlock the texture
  315.     m_pAlphaMap->UnlockRect(0);
  316.     
  317.     //D3DXSaveTextureToFile("alpha.bmp", D3DXIFF_BMP, m_pAlphaMap, NULL);
  318. }
  319.  
  320. void TERRAIN::CalculateLightMap()
  321. {
  322.     try
  323.     {
  324.         //Clear old alpha maps
  325.         if(m_pLightMap != NULL)
  326.             m_pLightMap->Release();
  327.  
  328.         //Create new light map
  329.         D3DXCreateTexture(m_pDevice, 256, 256, 1, D3DUSAGE_DYNAMIC, D3DFMT_L8, D3DPOOL_DEFAULT, &m_pLightMap);
  330.  
  331.         //Lock the texture
  332.         D3DLOCKED_RECT sRect;
  333.         m_pLightMap->LockRect(0, &sRect, NULL, NULL);
  334.         BYTE *bytes = (BYTE*)sRect.pBits;
  335.         memset(bytes, 255, 256*sRect.Pitch);        //Clear texture to white
  336.  
  337.         for(int y=0;y<sRect.Pitch;y++)
  338.         {
  339.             Progress("Calculating Lightmap", y / (float)sRect.Pitch);
  340.  
  341.             for(int x=0;x<sRect.Pitch;x++)
  342.             {
  343.                 float terrain_x = (float)m_size.x * (x / (float)(sRect.Pitch));
  344.                 float terrain_z = (float)m_size.y * (y / (float)(sRect.Pitch));
  345.  
  346.                 //Find patch that the terrain_x, terrain_z is over
  347.                 bool done = false;
  348.                 for(int p=0;p<m_patches.size() && !done;p++)
  349.                 {
  350.                     RECT mr = m_patches[p]->m_mapRect;
  351.  
  352.                     //Focus within patch maprect or not?
  353.                     if(terrain_x >= mr.left && terrain_x < mr.right &&
  354.                          terrain_z >= mr.top && terrain_z < mr.bottom)
  355.                     {            
  356.                         // Collect only the closest intersection
  357.                         RAY rayTop(D3DXVECTOR3(terrain_x, 10000.0f, -terrain_z), D3DXVECTOR3(0.0f, -1.0f, 0.0f));
  358.                         float dist = rayTop.Intersect(m_patches[p]->m_pMesh);
  359.  
  360.                         if(dist >= 0.0f)
  361.                         {
  362.                             RAY ray(D3DXVECTOR3(terrain_x, 10000.0f - dist + 0.01f, -terrain_z), m_dirToSun);
  363.  
  364.                             for(int p2=0;p2<m_patches.size() && !done;p2++)
  365.                                 if(ray.Intersect(m_patches[p2]->m_BBox) >= 0)
  366.                                 {
  367.                                     if(ray.Intersect(m_patches[p2]->m_pMesh) >= 0)    //In shadow
  368.                                     {
  369.                                         done = true;
  370.                                         bytes[y * sRect.Pitch + x] = 128;
  371.                                     }
  372.                                 }
  373.  
  374.                             done = true;
  375.                         }
  376.                     }
  377.                 }                        
  378.             }
  379.         }
  380.  
  381.         //Smooth lightmap        
  382.         for(int i=0;i<3;i++)
  383.         {
  384.             Progress("Smoothing the Lightmap", i / 3.0f);
  385.  
  386.             BYTE* tmpBytes = new BYTE[sRect.Pitch * sRect.Pitch];
  387.             memcpy(tmpBytes, sRect.pBits, sRect.Pitch * sRect.Pitch);
  388.  
  389.             for(int y=1;y<sRect.Pitch-1;y++)
  390.                 for(int x=1;x<sRect.Pitch-1;x++)
  391.                 {
  392.                     long index = y*sRect.Pitch + x;
  393.                     BYTE b1 = bytes[index];
  394.                     BYTE b2 = bytes[index - 1];
  395.                     BYTE b3 = bytes[index - sRect.Pitch];
  396.                     BYTE b4 = bytes[index + 1];
  397.                     BYTE b5 = bytes[index + sRect.Pitch];
  398.                     
  399.                     tmpBytes[index] = (BYTE)((b1 + b2 + b3 + b4 + b5) / 5);
  400.                 }
  401.  
  402.             memcpy(sRect.pBits, tmpBytes, sRect.Pitch * sRect.Pitch);
  403.             delete [] tmpBytes;
  404.         }
  405.  
  406.         //Unlock the texture
  407.         m_pLightMap->UnlockRect(0);
  408.         
  409.         //D3DXSaveTextureToFile("light.bmp", D3DXIFF_BMP, m_pLightMap, NULL);
  410.     }
  411.     catch(...)
  412.     {
  413.         debug.Print("Error in TERRAIN::CalculateLightMap()");
  414.     }
  415. }
  416.  
  417. D3DXVECTOR3 TERRAIN::GetNormal(int x, int y)
  418. {
  419.     //Neighboring map nodes (D, B, C, F, H, G)
  420.     INTPOINT mp[] = {INTPOINT(x-1, y),   INTPOINT(x, y-1), 
  421.                      INTPOINT(x+1, y-1), INTPOINT(x+1, y),
  422.                        INTPOINT(x, y+1),   INTPOINT(x-1, y+1)};
  423.  
  424.     //if there's an invalid map node return (0, 1, 0)
  425.     if(!Within(mp[0]) || !Within(mp[1]) || !Within(mp[2]) || 
  426.        !Within(mp[3]) || !Within(mp[4]) || !Within(mp[5]))
  427.         return D3DXVECTOR3(0.0f, 1.0f, 0.0f);
  428.  
  429.     //Calculate the normals of the 6 neighboring planes
  430.     D3DXVECTOR3 normal = D3DXVECTOR3(0.0f, 0.0f, 0.0f);
  431.  
  432.     for(int i=0;i<6;i++)
  433.     {
  434.         D3DXPLANE plane;
  435.         D3DXPlaneFromPoints(&plane, 
  436.                             &GetWorldPos(INTPOINT(x, y)),
  437.                             &GetWorldPos(mp[i]), 
  438.                             &GetWorldPos(mp[(i + 1) % 6]));
  439.  
  440.         normal +=  D3DXVECTOR3(plane.a, plane.b, plane.c);
  441.     }
  442.  
  443.     D3DXVec3Normalize(&normal, &normal);
  444.     return normal;
  445. }
  446.  
  447. void TERRAIN::AddObject(int type, INTPOINT mappos)
  448. {
  449.     D3DXVECTOR3 pos = D3DXVECTOR3(mappos.x, m_pHeightMap->GetHeight(mappos), -mappos.y);    
  450.     D3DXVECTOR3 rot = D3DXVECTOR3((rand()%1000 / 1000.0f) * 0.13f, (rand()%1000 / 1000.0f) * 3.0f, (rand()%1000 / 1000.0f) * 0.13);
  451.  
  452.     float sca_xz = (rand()%1000 / 1000.0f) * 0.5f + 0.5f;
  453.     float sca_y = (rand()%1000 / 1000.0f) * 1.0f + 0.5f;
  454.     D3DXVECTOR3 sca = D3DXVECTOR3(sca_xz, sca_y, sca_xz);
  455.  
  456.     m_objects.push_back(OBJECT(type, mappos, pos, rot, sca));
  457. }
  458.  
  459. void TERRAIN::Render(CAMERA &camera)
  460. {
  461.     //Set render states        
  462.     m_pDevice->SetRenderState(D3DRS_LIGHTING, false);
  463.     m_pDevice->SetRenderState(D3DRS_ZWRITEENABLE, true);    
  464.     
  465.     m_pDevice->SetTexture(0, m_pAlphaMap);
  466.     m_pDevice->SetTexture(1, m_diffuseMaps[0]);        //Grass
  467.     m_pDevice->SetTexture(2, m_diffuseMaps[1]);        //Mountain
  468.     m_pDevice->SetTexture(3, m_diffuseMaps[2]);        //Snow
  469.     m_pDevice->SetTexture(4, m_pLightMap);            //Lightmap
  470.     m_pDevice->SetMaterial(&m_mtrl);
  471.  
  472.     D3DXMATRIX world, vp = camera.GetViewMatrix() * camera.GetProjectionMatrix();
  473.     D3DXMatrixIdentity(&world);
  474.     m_pDevice->SetTransform(D3DTS_WORLD, &world);
  475.     
  476.     //Set vertex shader variables
  477.     m_terrainVS.SetMatrix(m_vsMatW, world);
  478.     m_terrainVS.SetMatrix(m_vsMatVP, vp);
  479.     m_terrainVS.SetVector3(m_vsDirToSun, m_dirToSun);
  480.  
  481.     m_terrainVS.Begin();
  482.     m_terrainPS.Begin();
  483.         
  484.     for(int p=0;p<m_patches.size();p++)
  485.         if(!camera.Cull(m_patches[p]->m_BBox))
  486.             m_patches[p]->Render();
  487.  
  488.     m_terrainPS.End();
  489.     m_terrainVS.End();
  490.  
  491.     m_pDevice->SetTexture(1, NULL);
  492.     m_pDevice->SetTexture(2, NULL);
  493.     m_pDevice->SetTexture(3, NULL);
  494.     m_pDevice->SetTexture(4, NULL);
  495.  
  496.     //Render Objects
  497.     m_objectVS.SetMatrix(m_objMatW, world);
  498.     m_objectVS.SetMatrix(m_objMatVP, vp);
  499.     m_objectVS.SetVector3(m_objDirToSun, m_dirToSun);
  500.     m_objectVS.SetVector3(m_objMapSize, D3DXVECTOR3(m_size.x, m_size.y, 0.0f));
  501.  
  502.     m_pDevice->SetTexture(1, m_pLightMap);        //Lightmap
  503.     
  504.     m_objectVS.Begin();
  505.     m_objectPS.Begin();
  506.  
  507.     for(int i=0;i<m_objects.size();i++)
  508.         if(!camera.Cull(m_objects[i].m_BBox))
  509.         {
  510.             D3DXMATRIX m = m_objects[i].m_meshInstance.GetWorldMatrix();
  511.             m_objectVS.SetMatrix(m_objMatW, m);
  512.             m_objects[i].Render();
  513.         }
  514.  
  515.     m_objectVS.End();
  516.     m_objectPS.End();
  517. }
  518.  
  519. void TERRAIN::Progress(std::string text, float prc)
  520. {
  521.     m_pDevice->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L);
  522.     m_pDevice->BeginScene();
  523.     
  524.     RECT rc = {200, 250, 600, 300};
  525.     m_pProgressFont->DrawText(NULL, text.c_str(), -1, &rc, DT_CENTER | DT_VCENTER | DT_NOCLIP, 0xff000000);
  526.     
  527.     //Progress bar
  528.     D3DRECT r;
  529.     r.x1 = 200; r.x2 = 600;
  530.     r.y1 = 300; r.y2 = 340;
  531.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff000000, 1.0f, 0L);
  532.     r.x1 = 202; r.x2 = 598;
  533.     r.y1 = 302; r.y2 = 338;
  534.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xffffffff, 1.0f, 0L);
  535.     r.x1 = 202; r.x2 = 202 + 396 * prc;
  536.     r.y1 = 302; r.y2 = 338;
  537.     m_pDevice->Clear(1, &r, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, 0xff00ff00, 1.0f, 0L);
  538.  
  539.     m_pDevice->EndScene();
  540.     m_pDevice->Present(0, 0, 0, 0);
  541. }
  542.  
  543. bool TERRAIN::Within(INTPOINT p)
  544. {
  545.     return p.x >= 0 && p.y >= 0 && p.x < m_size.x && p.y < m_size.y;
  546. }
  547.  
  548. void TERRAIN::InitPathfinding()
  549. {
  550.     try
  551.     {
  552.         //Read maptile heights & types from heightmap
  553.         for(int y=0;y<m_size.y;y++)
  554.             for(int x=0;x<m_size.x;x++)
  555.             {
  556.                 MAPTILE *tile = GetTile(x, y);
  557.                 if(m_pHeightMap != NULL)tile->m_height = m_pHeightMap->GetHeight(x, y);
  558.                 tile->m_mappos = INTPOINT(x, y);
  559.                 
  560.                 if(tile->m_height < 0.3f)         tile->m_type = 0;    //Grass
  561.                 else if(tile->m_height < 7.0f) tile->m_type = 1;    //Stone
  562.                 else                         tile->m_type = 2;    //Snow
  563.             }
  564.  
  565.         //Calculate tile cost as a function of the height variance
  566.         for(int y=0;y<m_size.y;y++)        
  567.             for(int x=0;x<m_size.x;x++)
  568.             {
  569.                 MAPTILE *tile = GetTile(x, y);
  570.  
  571.                 if(tile != NULL)
  572.                 {
  573.                     //Possible neighbors
  574.                     INTPOINT p[] = {INTPOINT(x-1, y-1), INTPOINT(x, y-1), INTPOINT(x+1, y-1),
  575.                                     INTPOINT(x-1, y),                      INTPOINT(x+1, y),
  576.                                     INTPOINT(x-1, y+1), INTPOINT(x, y+1), INTPOINT(x+1, y+1)};
  577.  
  578.                     float variance = 0.0f;
  579.                     int nr = 0;
  580.  
  581.                     //For each neighbor
  582.                     for(int i=0;i<8;i++)    
  583.                         if(Within(p[i]))
  584.                         {
  585.                             MAPTILE *neighbor = GetTile(p[i]);
  586.  
  587.                             if(neighbor != NULL)
  588.                             {
  589.                                 float v = neighbor->m_height - tile->m_height;
  590.                                 variance += (v * v);
  591.                                 nr++;
  592.                             }
  593.                         }
  594.  
  595.                     //Cost = height variance
  596.                     variance /= (float)nr;
  597.                     tile->m_cost = variance + 0.1f;
  598.                     if(tile->m_cost > 1.0f)tile->m_cost = 1.0f;
  599.  
  600.                     //If the tile cost is less than 1.0f, then we can walk on the tile
  601.                     tile->m_walkable = tile->m_cost < 0.5f;
  602.                 }
  603.             }
  604.  
  605.         //Make maptiles with objects on them not walkable
  606.         for(int i=0;i<m_objects.size();i++)
  607.         {
  608.             MAPTILE *tile = GetTile(m_objects[i].m_mappos);
  609.             if(tile != NULL)
  610.             {
  611.                 tile->m_walkable = false;
  612.                 tile->m_cost = 1.0f;
  613.             }
  614.         }
  615.  
  616.         //Connect maptiles using the neightbors[] pointers
  617.         for(int y=0;y<m_size.y;y++)        
  618.             for(int x=0;x<m_size.x;x++)
  619.             {
  620.                 MAPTILE *tile = GetTile(x, y);
  621.                 if(tile != NULL && tile->m_walkable)
  622.                 {
  623.                     //Clear old connections
  624.                     for(int i=0;i<8;i++)
  625.                         tile->m_pNeighbors[i] = NULL;
  626.  
  627.                     //Possible neighbors
  628.                     INTPOINT p[] = {INTPOINT(x-1, y-1), INTPOINT(x, y-1), INTPOINT(x+1, y-1),
  629.                                     INTPOINT(x-1, y),                      INTPOINT(x+1, y),
  630.                                     INTPOINT(x-1, y+1), INTPOINT(x, y+1), INTPOINT(x+1, y+1)};
  631.  
  632.                     //For each neighbor
  633.                     for(int i=0;i<8;i++)    
  634.                         if(Within(p[i]))
  635.                         {
  636.                             MAPTILE *neighbor = GetTile(p[i]);
  637.  
  638.                             //Connect tiles if the neighbor is walkable
  639.                             if(neighbor != NULL && neighbor->m_walkable)
  640.                                 tile->m_pNeighbors[i] = neighbor;
  641.                         }
  642.                 }
  643.             }
  644.  
  645.         CreateTileSets();
  646.     }
  647.     catch(...)
  648.     {
  649.         debug.Print("Error in InitPathfinding()");
  650.     }    
  651. }
  652.  
  653. void TERRAIN::CreateTileSets()
  654. {
  655.     try
  656.     {
  657.         int setNo = 0;
  658.         for(int y=0;y<m_size.y;y++)        //Set a unique set for each tile...
  659.             for(int x=0;x<m_size.x;x++)
  660.                 m_pMapTiles[x + y * m_size.x].m_set = setNo++;
  661.  
  662.         bool changed = true;
  663.         while(changed)
  664.         {
  665.             changed = false;
  666.  
  667.             for(int y=0;y<m_size.y;y++)
  668.                 for(int x=0;x<m_size.x;x++)
  669.                 {
  670.                     MAPTILE *tile = GetTile(x, y);
  671.  
  672.                     //Find the lowest set of a neighbor
  673.                     if(tile != NULL && tile->m_walkable)
  674.                     {
  675.                         for(int i=0;i<8;i++)
  676.                             if(tile->m_pNeighbors[i] != NULL &&
  677.                                 tile->m_pNeighbors[i]->m_walkable &&
  678.                                 tile->m_pNeighbors[i]->m_set < tile->m_set)
  679.                             {
  680.                                 changed = true;
  681.                                 tile->m_set = tile->m_pNeighbors[i]->m_set;
  682.                             }
  683.                     }
  684.                 }
  685.         }
  686.     }
  687.     catch(...)
  688.     {
  689.         debug.Print("Error in TERRAIN::CreateTileSets()");
  690.     }
  691. }
  692.  
  693. float H(INTPOINT a, INTPOINT b)
  694. {
  695.     //return abs(a.x - b.x) + abs(a.y - b.y);
  696.     return a.Distance(b);
  697. }
  698.  
  699. std::vector<INTPOINT> TERRAIN::GetPath(INTPOINT start, INTPOINT goal)
  700. {
  701.     try
  702.     {
  703.         //Check that the two points are within the bounds of the map
  704.         MAPTILE *startTile = GetTile(start);
  705.         MAPTILE *goalTile = GetTile(goal);
  706.  
  707.         if(!Within(start) || !Within(goal) || start == goal || startTile == NULL || goalTile == NULL)
  708.             return std::vector<INTPOINT>();
  709.  
  710.         //Check if a path exists
  711.         if(!startTile->m_walkable || !goalTile->m_walkable || startTile->m_set != goalTile->m_set)
  712.             return std::vector<INTPOINT>();
  713.  
  714.         //Init Search
  715.         long numTiles = m_size.x * m_size.y;
  716.         for(long l=0;l<numTiles;l++)
  717.         {
  718.             m_pMapTiles[l].f = m_pMapTiles[l].g = INT_MAX;        //Clear F,G
  719.             m_pMapTiles[l].open = m_pMapTiles[l].closed = false;    //Reset Open and Closed
  720.         }
  721.  
  722.         std::vector<MAPTILE*> open;                //Create Our Open list
  723.         startTile->g = 0;                        //Init our starting point (SP)
  724.         startTile->f = H(start, goal);
  725.         startTile->open = true;
  726.         open.push_back(startTile);                //Add SP to the Open list
  727.  
  728.         bool found = false;                    // Search as long as a path hasnt been found,
  729.         while(!found && !open.empty())        // or there is no more tiles to search
  730.         {                                                
  731.             MAPTILE * best = open[0];        // Find the best tile (i.e. the lowest F value)
  732.             int bestPlace = 0;
  733.             for(int i=1;i<open.size();i++)
  734.                 if(open[i]->f < best->f)
  735.                 {
  736.                     best = open[i];
  737.                     bestPlace = i;
  738.                 }
  739.             
  740.             if(best == NULL)break;            //No path found
  741.  
  742.             open[bestPlace]->open = false;
  743.             open.erase(&open[bestPlace]);    // Take the best node out of the Open list
  744.  
  745.             if(best->m_mappos == goal)        //If the goal has been found
  746.             {
  747.                 std::vector<INTPOINT> p, p2;
  748.                 MAPTILE *point = best;
  749.  
  750.                 while(point->m_mappos != start)    // Generate path
  751.                 {
  752.                     p.push_back(point->m_mappos);
  753.                     point = point->m_pParent;
  754.                 }
  755.  
  756.                 for(int i=p.size()-1;i!=0;i--)    // Reverse path
  757.                     p2.push_back(p[i]);
  758.                 p2.push_back(goal);
  759.                 return p2;
  760.             }
  761.             else
  762.             {
  763.                 for(i=0;i<8;i++)                    // otherwise, check the neighbors of the
  764.                     if(best->m_pNeighbors[i] != NULL)    // best tile
  765.                     {
  766.                         bool inList = false;        // Generate new G and F value
  767.                         float newG = best->g + 1.0f;
  768.                         float d = H(best->m_mappos, best->m_pNeighbors[i]->m_mappos);
  769.                         float newF = newG + H(best->m_pNeighbors[i]->m_mappos, goal) + best->m_pNeighbors[i]->m_cost * 5.0f * d;
  770.  
  771.                         if(best->m_pNeighbors[i]->open || best->m_pNeighbors[i]->closed)
  772.                         {
  773.                             if(newF < best->m_pNeighbors[i]->f)    // If the new F value is lower
  774.                             {
  775.                                 best->m_pNeighbors[i]->g = newG;    // update the values of this tile
  776.                                 best->m_pNeighbors[i]->f = newF;
  777.                                 best->m_pNeighbors[i]->m_pParent = best;                                
  778.                             }
  779.                             inList = true;
  780.                         }
  781.  
  782.                         if(!inList)            // If the neighbor tile isn't in the Open or Closed list
  783.                         {
  784.                             best->m_pNeighbors[i]->f = newF;        //Set the values
  785.                             best->m_pNeighbors[i]->g = newG;
  786.                             best->m_pNeighbors[i]->m_pParent = best;
  787.                             best->m_pNeighbors[i]->open = true;
  788.                             open.push_back(best->m_pNeighbors[i]);    //Add it to the open list    
  789.                         }
  790.                     }
  791.  
  792.                 best->closed = true;        //The best tile has now been searched, add it to the Closed list
  793.             }
  794.         }
  795.  
  796.         return std::vector<INTPOINT>();        //No path found, return an empty path
  797.         
  798.     }
  799.     catch(...)
  800.     {
  801.         debug.Print("Error in TERRAIN::GetPath()");
  802.         return std::vector<INTPOINT>();
  803.     }
  804. }
  805.  
  806. MAPTILE* TERRAIN::GetTile(int x, int y)
  807. {
  808.     if(m_pMapTiles == NULL)return NULL;
  809.  
  810.     try
  811.     {
  812.         return &m_pMapTiles[x + y * m_size.x];
  813.     }
  814.     catch(...)
  815.     {
  816.         return NULL;
  817.     }
  818. }
  819.  
  820. void TERRAIN::SaveTerrain(char fileName[])
  821. {
  822.     try
  823.     {
  824.         std::ofstream out(fileName, std::ios::binary);        //Binary format
  825.  
  826.         if(out.good())
  827.         {
  828.             out.write((char*)&m_size, sizeof(INTPOINT));    //Write map size
  829.  
  830.             //Write all the maptile information needed to recreate the map
  831.             for(int y=0;y<m_size.y;y++)
  832.                 for(int x=0;x<m_size.x;x++)
  833.                 {
  834.                     MAPTILE *tile = GetTile(x, y);
  835.                     out.write((char*)&tile->m_type, sizeof(int));            //type
  836.                     out.write((char*)&tile->m_height, sizeof(float));        //Height
  837.                 }
  838.  
  839.             //Write all the objects
  840.             int numObjects = m_objects.size();
  841.             out.write((char*)&numObjects, sizeof(int));     //Num Objects
  842.             for(int i=0;i<m_objects.size();i++)
  843.             {
  844.                 out.write((char*)&m_objects[i].m_type, sizeof(int));                        //type
  845.                 out.write((char*)&m_objects[i].m_mappos, sizeof(INTPOINT));                    //mappos
  846.                 out.write((char*)&m_objects[i].m_meshInstance.m_pos, sizeof(D3DXVECTOR3));    //Pos
  847.                 out.write((char*)&m_objects[i].m_meshInstance.m_rot, sizeof(D3DXVECTOR3));    //Rot
  848.                 out.write((char*)&m_objects[i].m_meshInstance.m_sca, sizeof(D3DXVECTOR3));    //Sca
  849.             }
  850.         }
  851.  
  852.         out.close();
  853.     }
  854.     catch(...)
  855.     {
  856.         debug.Print("Error in TERRAIN::SaveTerrain()");
  857.     }
  858. }
  859.  
  860. void TERRAIN::LoadTerrain(char fileName[])
  861. {
  862.     try
  863.     {
  864.         std::ifstream in(fileName, std::ios::binary);        //Binary format
  865.  
  866.         if(in.good())
  867.         {
  868.             Release();    //Release all terrain resources
  869.  
  870.             in.read((char*)&m_size, sizeof(INTPOINT));    //read map size
  871.         
  872.             if(m_pMapTiles != NULL)    //Clear old maptiles
  873.                 delete [] m_pMapTiles;
  874.  
  875.             //Create new maptiles
  876.             m_pMapTiles = new MAPTILE[m_size.x * m_size.y];
  877.             memset(m_pMapTiles, 0, sizeof(MAPTILE)*m_size.x*m_size.y);
  878.  
  879.  
  880.             //Read the maptile information
  881.             for(int y=0;y<m_size.y;y++)
  882.                 for(int x=0;x<m_size.x;x++)
  883.                 {
  884.                     MAPTILE *tile = GetTile(x, y);
  885.                     in.read((char*)&tile->m_type, sizeof(int));            //type
  886.                     in.read((char*)&tile->m_height, sizeof(float));        //Height
  887.                 }
  888.  
  889.             //Read number of objects
  890.             int numObjects = 0;
  891.             in.read((char*)&numObjects, sizeof(int));
  892.             for(int i=0;i<numObjects;i++)
  893.             {
  894.                 int type = 0;
  895.                 INTPOINT mp;
  896.                 D3DXVECTOR3 p, r, s;
  897.  
  898.                 in.read((char*)&type, sizeof(int));            //type
  899.                 in.read((char*)&mp, sizeof(INTPOINT));        //mappos
  900.                 in.read((char*)&p, sizeof(D3DXVECTOR3));    //Pos
  901.                 in.read((char*)&r, sizeof(D3DXVECTOR3));    //Rot
  902.                 in.read((char*)&s, sizeof(D3DXVECTOR3));    //Sca
  903.  
  904.                 m_objects.push_back(OBJECT(type, mp, p, r, s));
  905.             }
  906.  
  907.             //Recreate Terrain
  908.             InitPathfinding();
  909.             CreatePatches(3);
  910.             CalculateAlphaMaps();
  911.             CalculateLightMap();
  912.         }
  913.  
  914.         in.close();
  915.     }
  916.     catch(...)
  917.     {
  918.         debug.Print("Error in TERRAIN::LoadTerrain()");
  919.     }
  920. }
  921.  
  922. D3DXVECTOR3 TERRAIN::GetWorldPos(INTPOINT mappos)
  923. {
  924.     if(!Within(mappos))return D3DXVECTOR3(0, 0, 0);
  925.     MAPTILE *tile = GetTile(mappos);
  926.     return D3DXVECTOR3(mappos.x, tile->m_height, -mappos.y);
  927. }